package net.avh4.scratch.rpg;

import java.io.IOException;
import java.util.Random;

public class GeneratorWorldMap extends CachedWorldMap {
	
	private final Random rand;

	public GeneratorWorldMap() throws IOException {
		super();
		rand = new Random();
		// Seed the cache
		setTile(5,5,0);
		for (int i = 6; i < maxHeight || i < maxWidth; i++) {
			if (i < maxWidth) generateColumn(i, i-1);
			if (i < maxHeight) generateRow(i, i-1);
		}
		for (int i = 4; i >= 0; i--) {
			generateColumn(i, i+1);
			generateRow(i, i+1);
		}
	}
	
	private boolean generateColumn(int newCol, int basedOn) {
		if (Math.abs(newCol-basedOn) != 1) {
			throw new IllegalArgumentException("newCol must be adjacent to basedOn");
		}
		
		for (int y = 0; y < maxHeight; y++) {
			int baseType = getTile(basedOn,y);
			setTile(newCol, y, newType(baseType));
		}
	}
	
	private boolean generateRow(int newRow, int basedOn) {
		if (Math.abs(newRow-basedOn) != 1) {
			throw new IllegalArgumentException("newRow must be adjacent to basedOn");
		}
		
		for (int x = 0; x < maxWidth; x++) {
			int baseType = getTile(x, basedOn);
			setTile(x, newRow, newType(baseType));
		}
	}
	
	private int newType(int baseType) {
		int type = -1;
		if (baseType == 1) {
			type = 1;
		} else if (baseType == 0) {
			if (rand.nextFloat() < 0.75) {
				type = 0;
			} else {
				type = 1;
			}
		}
		return type;
	}

}
